# Create your views here.
from hakaze.wiki.models import *
from django import newforms as forms
from django.shortcuts import render_to_response
from django.core.exceptions import ObjectDoesNotExist
from datetime import datetime
from hakaze import settings
from django.template import RequestContext
from django.views.decorators.vary import vary_on_cookie

def gen_contextdata():
    """
       This method will generate a dictionary for storing
       inside the session context
    """
    tdict = {}
    tdict['tsettings'] = settings.TEMPLATE_VARS
    return tdict

class WikiForm(forms.Form):
     contents = forms.CharField(widget=forms.widgets.Textarea(attrs={'class' : 'wikientry'}))

@vary_on_cookie
def wikipage(response,pagetitle=None):
     if not pagetitle:
        pagetitle = settings.WIKI_FIRSTPAGE
     tdict={ 'pagetitle': pagetitle }
     page = None
     try:
        if not tdict.has_key('page'):
            tdict['page'] = page = WikiPage.objects.get(title=pagetitle)
     except ObjectDoesNotExist:
        pass

     if response.user.is_authenticated():
       if response.GET:
          try:
             if response.GET['edit'] == "1":
                if page: tdict['wikiform'] = WikiForm(initial={'contents':page.contents})
                else : tdict['wikiform'] = WikiForm()
          except:
             pass
       if response.POST:
          tdict['notice_messages'] = notices = []
          tdict['wikiform'] = f = WikiForm(response.POST)
          if f.is_valid():
             tdict['page'] = w = WikiPage(title=pagetitle,
                                          contents=f.clean_data['contents'], 
                                          last_edited_by=response.user.username,
                                          last_edited_on=datetime.now())
             if response.POST['submit'].lower() == "submit":
                w.save()
                notices.append('Wiki Page Edited')
                tdict['pagerefresh'] = {'timeout':5000}
                return render_to_response('refresh.html',tdict,context_instance=RequestContext(response, gen_contextdata()))


     return render_to_response('wiki/wikipage.html',tdict,context_instance=RequestContext(response,gen_contextdata()))
